package com.example.file.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import entity.Rsp;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public Rsp uploadImage(MultipartFile image) {
        //对文件后缀名进行校验  一般前端校验比较好可以减轻后端压力  但是后端是最后一道防线也需要校验


        File toFile = new File(image.getOriginalFilename());

        try {
            FileUtils.copyInputStreamToFile(image.getInputStream(),toFile);
        } catch (IOException e) {
            e.printStackTrace();
            return Rsp.fail().msg("文件上传失败 原因：io错误");
        }




        return uploudToAliyunOss(toFile);
    }

    @Override
    public Rsp uploudToAliyunOss(File file) {


        String endpoint = "http://oss-cn-shanghai.aliyuncs.com";

        String accessKeyId = "LTAI4FyrvZQtmnQriUF3x8ui";
        String accessKeySecret = "WnN61YbCd9sn7b5GK0beQu7a79meZJ";

        String bucketName = "wnbucket";


        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String fileKey = System.currentTimeMillis()+file.getName();

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileKey, file);
            //上传成功  删除业务服务器 本地的文件
            file.delete();
        }catch (Exception e){
            e.printStackTrace();
            return Rsp.fail().msg("文件转储aliyun失败");
        }




        return Rsp.success("https://wnbucket.oss-cn-shanghai.aliyuncs.com/"+fileKey);
    }
}
